package cc.htdf.gwc.radar.config.init;

import cc.htdf.gwc.radar.config.constants.Constants;
import cc.htdf.gwc.radar.domain.GridInfo;
import cc.htdf.gwc.radar.service.StationInfoService;
import com.google.common.base.Optional;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.DecimalFormat;
import java.util.List;

/**
 * Created by JT on 2017/11/13.
 */
@Component
public class ForecastLatlonGrid {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private StationInfoService stationInfoService;


    @PostConstruct
    public void initForecastLatlonGrid() {

        logger.info("开始加载成都国家站临近格点!");

        DecimalFormat latLonFormat= new DecimalFormat("##0.0000");

        int latLength = 2100, lonLength = 3100;
        double latMin = 12.204999923706055, lonMin = 73.004997253417970;
        double latDelta = 0.019999999552965, lonDelta = 0.019999999552965;
        String latStr, lonStr;

        /**
         * 加载站点临近格点
         */
        List<GridInfo> gridInfos = stationInfoService.findGridInfos();
        Table<String, String, String> gridLatlonTable = HashBasedTable.create();
        for (GridInfo info: gridInfos)
            gridLatlonTable.put(info.getLat().trim(), info.getLon().trim(), info.getNearStation().trim());


        // Table row: 临近站站号 col: 经纬度[0:纬度;1:经度] value:对应位置[0:i,1:j]
        Table<String, String[], int[]> gridInfoTable = HashBasedTable.create();
        for (int i = 0; i < latLength; i++) {
            double lat = latMin + latDelta * i;

            for (int j = 0; j < lonLength; j++) {
                double lon = lonMin + lonDelta * j;

                latStr = latLonFormat.format(lat);
                lonStr = latLonFormat.format(lon);

                String stationId = gridLatlonTable.get(latStr, lonStr);
                if (Optional.fromNullable(stationId).isPresent()) {
                    gridInfoTable.put(stationId, new String[]{latStr, lonStr}, new int[]{i, j});
                }

            }

        }

        // 加载到常量池
        Constants.GRID_INFO_TABLE = gridInfoTable;
        logger.info("结束加载成都国家站临近格点!");


    }



}
